<template>
  <div class="assignee-config">
    <PersonnelConfig
      :assignees="assignees"
      @openSelector="handleOpenSelector"
      @update:assignees="handleAssigneesUpdate"
    />
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import PersonnelConfig from '@/views/workflow/process/components/configs/PersonnelConfig.vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'openSelector'])

// 人员配置数据
const assignees = ref([...props.modelValue])

// 防止递归更新的标志
const isUpdating = ref(false)

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (!isUpdating.value) {
    assignees.value = [...newValue]
  }
}, { deep: true })

// 处理PersonnelConfig的update:assignees事件
const handleAssigneesUpdate = (newAssignees) => {
  if (!isUpdating.value) {
    isUpdating.value = true
    
    // 直接更新数据
    assignees.value = newAssignees
    
    // 直接触发事件
    nextTick(() => {
      emit('update:modelValue', assignees.value)
      emit('change', assignees.value)
      isUpdating.value = false
    })
  }
}

// 处理打开选择器事件
const handleOpenSelector = (data) => {
  // 这里可以添加其他处理逻辑，比如日志记录等
  emit('open-selector', data)
}

// 暴露方法给父组件
defineExpose({
  getAssignees: () => assignees.value,
  setAssignees: (newAssignees) => {
    if (!isUpdating.value) {
      isUpdating.value = true
      assignees.value = [...newAssignees]
      nextTick(() => {
        isUpdating.value = false
      })
    }
  },
  reset: () => {
    if (!isUpdating.value) {
      isUpdating.value = true
      assignees.value = []
      nextTick(() => {
        isUpdating.value = false
      })
    }
  }
})
</script>

<style scoped>
.assignee-config {
  width: 100%;
}
</style> 